package com.earl.eatbao.service.impl;

import javax.annotation.Resource;

import com.earl.eatbao.dao.UserDao;
import com.earl.eatbao.dao.eatbao.ShopDao;
import com.earl.eatbao.domain.eatbao.Shop;
import com.earl.eatbao.domain.sercurity.User;
import com.earl.eatbao.exception.DomainSecurityException;
import com.earl.eatbao.util.CheckCodeUtils;
import com.earl.eatbao.util.UpLoadFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.earl.eatbao.commons.dao.BaseRepsitoty;
import com.earl.eatbao.commons.service.BaseServiceImpl;
import com.earl.eatbao.dao.eatbao.ShopperDao;
import com.earl.eatbao.domain.eatbao.Shopper;
import com.earl.eatbao.service.ShopperService;
import org.springframework.web.multipart.MultipartFile;


import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service("shopperService")
public class ShopperServiceImpl extends BaseServiceImpl<Shopper, Long> implements ShopperService {

    // desc:日记工具logger
    private static final Logger logger = LoggerFactory.getLogger(ShopperServiceImpl.class);

    @Resource
    private ShopperDao shopperDao;

    @Autowired
    private ShopDao shopDao;

    @Override
    protected BaseRepsitoty<Shopper, Long> getDao() {
        return shopperDao;
    }


    @Override
    public Boolean isShopper(Long userId) {
        logger.info("<====== 进入isShopper:方法,{[userId] :" + userId + " } ====");
        Shopper shopper = shopperDao.findUniqueByUserIdAndStatus(userId, 2);
        if (null != shopper) {
            logger.info("===== 退出isShopper:方法返回值类型:{ Boolean: true} ====>");
            return true;
        }
        logger.info("===== 退出isShopper:方法返回值类型:{ Boolean:false } ====>");
        return false;
    }

    @Override
    public List<Shopper> findAllShoper() {
        logger.info("<==== 进入findAllShoper:方法携带参数{[] : } =====");
        logger.info("===== 退出findAllShoper:方法返回值类型:{ List<Shopper>: } ====>");
        return (List<Shopper>) shopperDao.findAll();
    }

    @Override
    public Shopper beShopperApply(Shopper shopper,
                                  String checkCode,
                                  MultipartFile backImg,
                                  MultipartFile fontImg) {
        logger.info("<==== 进入beShopperApply:方法,{[dese, userId] : " + checkCode + "} ====");

        if(null == shopper || null == shopper.getContact() ) {
            new DomainSecurityException("上传信息有误！");
        }

        Shopper temShopper = shopperDao.findUniqueByContactAndIsDeleteFalse(shopper.getContact());

        if(temShopper == null || (temShopper != null && temShopper.getStatus() == 3)) {
            //检查验证码
            if (!CheckCodeUtils.checkCode(shopper.getContact(), checkCode)) {
                logger.error("==== 验证码错误 ====");
                return null;
            }

            String backImage = UpLoadFile.saveFile(backImg, UUID.randomUUID().toString());
            if (null != backImage) {
                shopper.setIdentityBackImg(backImage);
            } else {
                logger.error("==== 退出beShopperApply方法 返回值类型:{ Shopper: null} =======>");
                return null;
            }

            String fontImage = UpLoadFile.saveFile(fontImg, UUID.randomUUID().toString());
            if (null != fontImage) {
                shopper.setIdentityImg(fontImage);
            } else {
                logger.error("==== 退出beShopperApply方法 返回值类型:{ Shopper: null} =======>");
                return null;
            }

            shopper.setStatus(1);
            shopper.setDelete(false);
            shopper.setCreatedBy(shopper.getUserId() + "");
            shopper.setCreatedDate(new Date());
            shopper.setLastModifiedBy(shopper.getUserId() + "");
            shopper.setLastModifiedDate(new Date());
            //删除之前的数据
            if (0l != shopper.getUserId() && null != shopper.getName()) {
                shopperDao.deleteByUserId(shopper.getUserId());
            } else {
                logger.error("==== 用户Id不能为0 ====");
                return null;
            }
            logger.info("===== 退出beShopperApply:方法返回值类型:{ Shopper: 操作成功} ====>");
            return shopperDao.save(shopper);
        } else {
            new DomainSecurityException("该手机好已被使用，或者商家信息填写有误");
        }
        logger.info("==== 退出beShopperApply方法 返回值类型:{ Boolen : null } =======>");
        return null;
    }

    @Override
    public List<Shopper> findShopperByName(String shopName) {
        logger.info("<==== 进入findShopperByName:方法携带参数{[shopName] :" + shopName + " } =====");
        logger.info("===== 退出findShopperByName:方法返回值类型:{ List<Shopper>: } ====>");
        return shopperDao.findByName(shopName);
    }

    @Override
    public Boolean failOnShopperApply(Long applyId) {
        logger.info("<====== 进入failOnShopperApply:方法,{[applyId] :" + applyId + " } ====");
        Boolean result = changeShopperApplyStatus(applyId, 3);
        logger.info("==== 退出failOnShopperApply方法 返回值类型:{ Boolean :" + result + " } =======>");
        return result;
    }

    @Override
    public Boolean successOnShopperApply(Long applyId) {
        logger.info("<====== 进入successOnShopperApply:方法,{[applyId] :" + applyId + " } ====");
        Boolean result = changeShopperApplyStatus(applyId, 2);
        Shopper shopper = shopperDao.findOne(applyId);
        if (null != shopper) {
            Shop shop = new Shop();
            shop.setStatus(2);
            shop.setShopImg(null);
            shop.setCreatedBy(shopper.getUserId() + "");
            shop.setCreatedDate(new Date());
            shop.setLastModifiedDate(new Date());
            shop.setLastModifiedBy(shopper.getUserId() + "");
            shop.setStartingPrice(12);
            shop.setDistributionFee(2);
            shop.setBusinessId(shopper.getId());
            shop.setLatitude(12.0);
            shop.setLongitude(13.0);
            shop.setShopName(shopper.getName());
            shop.setOpenTime("8:00");
            shop.setStopTime("8:00");

            shopDao.save(shop);
        }

        logger.info("==== 退出successOnShopperApply方法 返回值类型:{ Boolean :" + result + " } =======>");
        return result;
    }

    @Override
    public List<Shopper> findAllWaitApplyShopper() {
        return shopperDao.findByStatus(1);
    }

    @Override
    public List<Shopper> findAllPassApplyShopper() {
        return shopperDao.findByStatus(2);
    }

    @Override
    public List<Shopper> findAllFailApplyShopper() {
        return shopperDao.findByStatus(3);
    }

    @Override
    public Shopper getBusinessStatus(Long userId) {
        if (null != userId)
            return shopperDao.findOneByUserId(userId);
        return null;
    }

    @Override
    public Boolean deleteShopperById(Long id) {
        logger.info("<====== 进入deleteShopperById:方法,{[id] :" + id + " } ====");
        Shopper shopper = shopperDao.findOne(id);
        Boolean result = false;
        if (null != shopper && shopper.getStatus() == 3) {
            shopperDao.delete(id);
            result = true;
        } else {
            logger.error("==== 非法删除商家 ====");
        }
        logger.info("==== 退出deleteShopperById方法 返回值类型:{Boolean:" + result + " } =======>");
        return result;
    }

    /**
     * 更改商家注册的状态
     *
     * @param applyId
     * @param status
     */
    private Boolean changeShopperApplyStatus(Long applyId, int status) {
        Shopper shopper = shopperDao.findOne(applyId);
        Boolean result = false;
        if (null != shopper) {
            if (shopper.getStatus() == 1 && status > 1) {
                shopper.setStatus(status);
                shopperDao.save(shopper);
                result = true;
            } else {
                logger.error("==== 非法改变注册商家信息 ====");
            }
        } else {
            logger.error("==== 该申请不存在 =====");
        }
        return result;
    }

}